//
//  Utils.m
//  Cunli
//
//  Created by lilubin on 15/7/2.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "Utils.h"

@implementation Utils

//压缩图片大小
+ (NSData *)compressImage:(UIImage *)image
{
    CGSize size = [self scaleSize:image.size];
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSUInteger maxFileSize = 50 * 1024;
    CGFloat compressionRatio = 0.7f;
    CGFloat maxCompressionRatio = 0.1f;
    
    NSData *imageData = UIImageJPEGRepresentation(scaledImage, compressionRatio);
    
    while (imageData.length > maxFileSize && compressionRatio > maxCompressionRatio) {
        compressionRatio -= 0.1f;
        imageData = UIImageJPEGRepresentation(image, compressionRatio);
    }
    
    return imageData;
}

+ (CGSize)scaleSize:(CGSize)sourceSize
{
    float width = sourceSize.width;
    float height = sourceSize.height;
    if (width >= height) {
        return CGSizeMake(800, 800 * height / width);
    } else {
        return CGSizeMake(800 * width / height, 800);
    }
}

//压缩图片尺寸
+(UIImage *)sizeCompressImageTo1024With:(UIImage *)image
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = 1024;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth / width;
    float heightScale = imageHeight / height;
    
    //创建bitmap的context，并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth/heightScale, height)];
    }
    else
    {
        [image drawInRect:CGRectMake(0, 0, width, imageHeight/widthScale)];
    }
    
    //从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //使当前context出堆栈
    UIGraphicsEndImageContext();
    return newImage;
}


@end
